package com.nai365.nart.pay.controller;

import cn.hutool.core.lang.Console;
import com.alibaba.fastjson15.JSONObject;
import com.nai365.nart.common.core.constant.SecurityConstants;
import com.nai365.nart.common.core.util.R;
import com.nai365.nart.common.log.annotation.SysLog;
import com.nai365.nart.common.security.annotation.Inner;
import com.nai365.nart.order.api.feign.OrderFeignService;
import com.nai365.nart.pay.entity.Order;
import com.nai365.nart.pay.entity.PayOnBehalf;
import com.nai365.nart.pay.service.PayService;
import com.nai365.nart.pay.vo.PayOnBehalfRetuenVo;
import com.nai365.nart.pay.vo.PayOrderResVo;
import com.upay.sdk.CipherWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequiredArgsConstructor
@RequestMapping("/pay")
@Api(value = "pay", tags = "订单支付")
public class UPayController {
	private static final String ENCRYPT_KEY = "encryptKey";
	private static final String MERCHANT_ID = "894363429";


	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@Autowired
	private PayService payService;

	private final OrderFeignService orderFeignService;

	@ApiOperation(value = "订单支付", notes = "订单支付")
	@SysLog("订单支付")
	@PostMapping("/orderPay")
	@Inner
	public R<String> payOrder(@RequestBody Order order) {
		R<com.nai365.nart.order.entity.Order> orderByOrderId = orderFeignService.findOrderByOrderId(order.getRequestId(), SecurityConstants.FROM_IN);
		com.nai365.nart.order.entity.Order data = orderByOrderId.getData();
		if(data.getStatus()!=0){
			return R.failed("订单已支付!","订单已支付! 或已失效！");
		}
		return R.ok(payService.genPayUrl(order));
	}


	@ApiOperation(value = "订单支付online", notes = "订单支付online")
	@PostMapping("/orderPayOnline")
	//@Inner(false)
	public R<String> orderPayOnline(@RequestBody Order order) {
		return R.ok(payService.genPayUrl(order));
	}

	/**
	 * 订单支付查询
	 */

	@ApiOperation(value = "订单支付查询", notes = "订单支付查询")
	@GetMapping("/findPayOrderByOderId/{orderId}")
	public R<PayOrderResVo> findPayOrderByOderId(@PathVariable("orderId") String orderId) {
		PayOrderResVo payOrderResVo = payService.findPayOrderByOderId(orderId);
		return R.ok(payOrderResVo);
	}

	/**
	 * 代付提现功能
	 */
	@ApiOperation(value = "代付提现", notes = "代付提现")
	@PostMapping("/PayOnBehalf")
	public R<Map<String, String>> PayOnBehalf(@RequestBody PayOnBehalf payOnBehalf) {
		R<Map<String, String>> mapR = payService.PayOnBehalf(payOnBehalf);
		return mapR;
	}

	/**
	 * 代付查询
	 */
	@ApiOperation(value = "代付查询", notes = "代付查询")
	@GetMapping("/findOnBehalfByOderId/{orderId}")
	public R<PayOnBehalfRetuenVo> findOnBehalfByOderId(@PathVariable("orderId") String orderId) {
		PayOnBehalfRetuenVo payOnBehalfRetuenVo = payService.findOnBehalfByOderId(orderId);
		return R.ok(payOnBehalfRetuenVo);
	}

	/**
	 * 代付回调
	 *
	 * @param payOrderTo
	 * @param encryptKey
	 */
	@PostMapping("/payOnBehalfRes")
	@Inner(false)
	public void PayOnBehalfRes(@RequestBody JSONObject payOrderTo, @RequestHeader(value = "encryptKey") String encryptKey) {

		payOrderTo.put(ENCRYPT_KEY, encryptKey);
		payOrderTo.put("merchantId", MERCHANT_ID);
		JSONObject j_data = CipherWrapper.bothDecryptWrap(payOrderTo);
		String jsonString = j_data.toJSONString();

		JSONObject jsonObject = JSONObject.parseObject(jsonString);

		String requestId = jsonObject.getString("requestId");

		String redisOrderId = stringRedisTemplate.opsForValue().get(requestId);

		if (!StringUtils.hasLength(redisOrderId)) {
			stringRedisTemplate.opsForValue().set(requestId, "1", 3L, TimeUnit.DAYS);
			orderFeignService.payCallback(jsonString, SecurityConstants.FROM_IN);
		}

	}

	/**
	 * 订单支付回调
	 *
	 * @param payOrderTo
	 * @param encryptKey
	 */
	@Inner(false)
	@PostMapping("/orderPayRes")
	public void orderPayRes(@RequestBody JSONObject payOrderTo, @RequestHeader(value = "encryptKey") String encryptKey) {
		Console.log("################################orderPayRes");

		payOrderTo.put(ENCRYPT_KEY, encryptKey);
		payOrderTo.put("merchantId", MERCHANT_ID);
		JSONObject j_data = CipherWrapper.bothDecryptWrap(payOrderTo);
		String jsonString = j_data.toJSONString();
		JSONObject jsonObject = JSONObject.parseObject(jsonString);
		System.out.println(jsonObject.toJSONString());
		String requestId = jsonObject.getString("requestId");

		String redisOrderId = stringRedisTemplate.opsForValue().get(requestId);

		if (!StringUtils.hasLength(redisOrderId)) {
			//上链操作
			payService.onChain(requestId);
			stringRedisTemplate.opsForValue().set(requestId, "1", 3L, TimeUnit.DAYS);
			orderFeignService.drawCallback(jsonString, SecurityConstants.FROM_IN);
		}
	}

}
